#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe 
#
# Distributed under terms of the MIT license.


import sys
import os

project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(project_path)
print project_path

from esr_parser import core
from esr_parser.parsers import detail
from esr_parser.models import KeywordTask
from Task.models import Task
import requests
from django.test import TestCase

class esrTest(TestCase):
    def test_get_id(self):
        url = 'https://world.taobao.com/item/528835992185.htm?fromSite=main'
        d_id = core.get_item_id(url)
        assert d_id == u'528835992185', '{} '
        url = 'https://world.taobao.com/item/521682100254.htm?fromSite=main&pvid=a0ddbe47-9237-46ca-860e-3bab253b0d1e'
        d_id = core.get_item_id(url)
        assert d_id == u'521682100254'
        url = 'https://world.tmall.com/item/529101024223.htm?spm=a312a.7700714.0.0.U4keTG&sku_properties=10004:709990523;5919063:6536025'
        d_id = core.get_item_id(url)
        assert d_id == u'529101024223'
        url = 'http://detail.m.tmall.com/item.htm?spm=0.0.0.0.QdzvZF&id=522157359219&sid=4992eb8e66f4909a1adaa1fdb8cc85d6&rn=849e410ccdaef4b28371f2c47718d6a6&abtest=7'
        d_id = core.get_item_id(url)
        assert d_id == u'522157359219'
        url = 'm.intl.taobao.com/detail/detail.html?spm=0.0.0.0.vEFW04&id=529091666938&sid=e6ab1fd1e09cb8fd2120b6b153c8b47e&rn=e905b22ea88963ef8994c7a50de1fa6e&abtest=28'
        d_id = core.get_item_id(url)
        assert d_id == u'529091666938'
        url = 'http://a.m.taobao.com/i41919276717.htm?spm=0.0.0.0.OZMEne&sid=951034ee11a131dc6ae40d69de5446c7&rn=841934052627e4ba4d9340130c5cf62a&abtest=29'
        d_id = core.get_item_id(url)
        assert d_id == u'41919276717'


    def _test_network(self):
        resp = requests.get('https://detail.tmall.com/item.htm?spm=a230r.1.14.62.jA2e8o&id=520331387374&ns=1&abbucket=16')
        assert not 'world.tmall' in resp.url, 'network error'

    def test_get_stock(self):
        result = detail.get_stock('522157359219')

    def test_create_keyword(self):
        keyword_task = KeywordTask(keyword='iphone')
        keyword_task.save()

        assert keyword_task.tasks.filter(live=True).count() == 24
